<?php
/* ========== ########## ========== ########## ========== ########## ========== */
/*                                                                              */
/*   WHMCS v4.1.2 NULLED R4 by FLIPMODE  [ BAD SYNTAX ]                         */
/*                                                                              */
/*                             INTERNAL BAD SYNTAX NULLED VERSION: 2.5.9.6 R4   */
/*                                                                              */
/*   ALL files have been analysed, cleaned and nulled of:                       */
/*     - Call Backs  (100%)                                                     */
/*     - Link Backs (95%)                                                       */
/*     - Licensing  (100%)                                                      */
/*     - Remote Links + URL's                                                   */
/*                                                                              */
/*   WHMCS v4.1.2 RELEASED: 4th November 2009                                   */
/*    -> FIRST v4.1.2 NULL R1: 19th November 2009                               */
/*    -> UPDATED v4.1.2 NULL R4: 27th November 2009                             */
/*                                                                              */
/*   TESTING + VERIFICATION::                                                   */
/*     Files Cleaned, Nulled, Checked, Verified By:                             */
/*      -> FLIPMODE!                                                            */
/*     Decoded By:                                                              */
/*      -> FLIPMODE! + Unknown Decoder                                          */
/*     Tested By:                                                               */
/*      -> FLIPMODE!, LeetWolf, and 12 Anonymous Users...                       */
/*     WHMCS 4.1.2 Supplied By:                                                 */
/*      -> WHM CompleteShit Coder @ WHMCS.com                                   */
/*                                                                              */
/*                                                                              */
/*   IMPORTANT NOTE::                                                           */
/*   PLEASE NOTE THIS IS FOR TRIAL PURPOSES ONLY!                               */
/*                          LIKE IT? THEN BUY IT!                               */
/*                                                                              */
/* ========== ########## ========== ########## ========== ########## ========== */

function getinvoicestatuscolour ($status)
{
	global $_LANG;
	if ($status == 'Unpaid')
	{
		$status = '<span class="textred">' . $_LANG['invoicesunpaid'] . '</span>';
	}
	else
	{
		if ($status == 'Paid')
		{
			$status = '<span class="textgreen">' . $_LANG['invoicespaid'] . '</span>';
		}
		else
		{
			if ($status == 'Cancelled')
			{
				$status = '<span class="textgrey">' . $_LANG['invoicescancelled'] . '</span>';
			}
			else
			{
				if ($status == 'Refunded')
				{
					$status = '<span class="textblack">' . $_LANG['invoicesrefunded'] . '</span>';
				}
				else
				{
					if ($status == 'Collections')
					{
						$status = '<span class="textgold">' . $_LANG['invoicescollections'] . '</span>';
					}
				}
			}
		}
	}

	return $status;
}

function getinvoicepayuntildate ($nextduedate, $billingcycle, $fulldate = '')
{
	$year = substr ($nextduedate, 0, 4);
	$month = substr ($nextduedate, 5, 2);
	$day = substr ($nextduedate, 8, 2);
	$daysadjust = 0;
	if (!$fulldate)
	{
		$daysadjust = 1;
	}

	if ($billingcycle == 'Monthly')
	{
		$new_time = mktime (0, 0, 0, $month + 1, $day - $daysadjust, $year);
	}
	else
	{
		if ($billingcycle == 'Quarterly')
		{
			$new_time = mktime (0, 0, 0, $month + 3, $day - $daysadjust, $year);
		}
		else
		{
			if ($billingcycle == 'Semi-Annually')
			{
				$new_time = mktime (0, 0, 0, $month + 6, $day - $daysadjust, $year);
			}
			else
			{
				if ($billingcycle == 'Annually')
				{
					$new_time = mktime (0, 0, 0, $month, $day - $daysadjust, $year + 1);
				}
				else
				{
					if ($billingcycle == 'Biennially')
					{
						$new_time = mktime (0, 0, 0, $month, $day - $daysadjust, $year + 2);
					}
				}
			}
		}
	}

	if ($billingcycle != 'One Time')
	{
		$invoicepayuntildate = date ('Y-m-d', $new_time);
	}

	return $invoicepayuntildate;
}

function addtransaction ($userid, $currencyid, $description, $amountin, $fees, $amountout, $gateway = '', $transid = '', $invoiceid = '', $date = '', $refundid = '', $rate = '')
{
	if ($date)
	{
		$date = tomysqldate ($date);
	}
	else
	{
		$date = 'now()';
	}

	if ($userid)
	{
		$currency = getcurrency ($userid);
		$currencyid = $currency['id'];
	}

	if (!$rate)
	{
		$result = select_query ('tblcurrencies', 'rate', array ('id' => $currencyid));
		$data = mysql_fetch_array ($result);
		$rate = $data['rate'];
	}

	if ($userid)
	{
		$currencyid = 0;
	}

	$array = array ('userid' => $userid, 'currency' => $currencyid, 'gateway' => $gateway, 'date' => $date, 'description' => $description, 'amountin' => $amountin, 'fees' => $fees, 'amountout' => $amountout, 'rate' => $rate, 'transid' => $transid, 'invoiceid' => $invoiceid, 'refundid' => $refundid);
	$saveid = insert_query ('tblaccounts', $array);
	logactivity ('' . 'Added Transaction - Transaction ID: ' . $saveid);
	$array['id'] = $saveid;
	run_hook ('afterAddTransaction', $array);
}

function updateinvoicetotal ($id)
{
	global $CONFIG;
	$result = select_query ('tblinvoiceitems', '', array ('invoiceid' => $id));
	while ($data = mysql_fetch_array ($result))
	{
		if ($data['taxed'] == '1')
		{
			$taxsubtotal += $data['amount'];
			continue;
		}
		else
		{
			$nontaxsubtotal += $data['amount'];
			continue;
		}
	}

	$subtotal = $nontaxsubtotal + $taxsubtotal;
	$result = select_query ('tblinvoices', 'userid,credit,taxrate,taxrate2', array ('id' => $id));
	$data = mysql_fetch_array ($result);
	$userid = $data['userid'];
	$credit = $data['credit'];
	$taxrate = $data['taxrate'];
	$taxrate2 = $data['taxrate2'];
	if (!function_exists ('getClientsDetails'))
	{
		require_once dirname (__FILE__) . '/clientfunctions.php';
	}

	$clientsdetails = getclientsdetails ($userid);
	$tax = 0;
	$tax2 = 0;
	if (($CONFIG['TaxEnabled'] == 'on' AND !$clientsdetails['taxexempt']))
	{
		if ($taxrate != '0.00')
		{
			if ($CONFIG['TaxType'] == 'Inclusive')
			{
				$taxrate = $taxrate / 100 + 1;
				$calc1 = $taxsubtotal / $taxrate;
				$tax = $taxsubtotal - $calc1;
				$subtotal -= $tax;
			}
			else
			{
				$taxrate = $taxrate / 100;
				$tax = $taxsubtotal * $taxrate;
			}
		}

		if ($taxrate2 != '0.00')
		{
			if ($CONFIG['TaxL2Compound'])
			{
				$taxsubtotal += $tax;
			}

			if ($CONFIG['TaxType'] == 'Inclusive')
			{
				$taxrate2 = $taxrate2 / 100 + 1;
				$calc1 = $taxsubtotal / $taxrate2;
				$tax2 = $taxsubtotal - $calc1;
				$subtotal -= $tax2;
			}
			else
			{
				$taxrate2 = $taxrate2 / 100;
				$tax2 = $taxsubtotal * $taxrate2;
			}
		}

		$tax = round ($tax, 2);
		$tax2 = round ($tax2, 2);
	}

	$total = $subtotal + $tax + $tax2;
	if (0 < $credit)
	{
		if ($total < $credit)
		{
			$total = 0;
			$remainingcredit = $total - $credit;
		}
		else
		{
			$total -= $credit;
		}
	}

	$subtotal = format_as_currency ($subtotal);
	$tax = format_as_currency ($tax);
	$total = format_as_currency ($total);
	update_query ('tblinvoices', array ('subtotal' => $subtotal, 'tax' => $tax, 'tax2' => $tax2, 'total' => $total), array ('id' => $id));
	run_hook ('UpdateInvoiceTotal', array ('invoiceid' => $id));
}

function addinvoicepayment ($invoiceid, $transid, $amount, $fees, $gateway, $noemail = '', $date = '')
{
	$result = select_query ('tblinvoices', 'userid,total,status', array ('id' => $invoiceid));
	$data = mysql_fetch_array ($result);
	$userid = $data['userid'];
	$total = $data['total'];
	$status = $data['status'];
	$result = select_query ('tblaccounts', 'SUM(amountin)-SUM(amountout)', array ('invoiceid' => $invoiceid));
	$data = mysql_fetch_array ($result);
	$amountpaid = $data[0];
	$balance = $total - $amountpaid;
	if (!$amount)
	{
		$amount = $balance;
		if ($amount <= 0)
		{
			return false;
		}
	}

	addtransaction ($userid, 0, 'Invoice Payment', $amount, $fees, 0, $gateway, $transid, $invoiceid, $date);
	$balance = format_as_currency ($balance);
	$amount = format_as_currency ($amount);
	$balance -= $amount;
	logactivity ('' . 'Added Invoice Payment - Invoice ID: ' . $invoiceid);
	run_hook ('AddInvoicePayment', array ('invoiceid' => $invoiceid));
	if (($balance <= 0 AND $status == 'Unpaid'))
	{
		processpaidinvoice ($invoiceid, $noemail);
	}
	else
	{
		if (!$noemail)
		{
			sendmessage ('Invoice Payment Confirmation', $invoiceid);
		}
	}

	if ($balance <= 0)
	{
		$result2 = select_query ('tblcredit', 'sum(amount)', array ('relid' => $invoiceid));
		$data2 = mysql_fetch_array ($result2);
		$amountcredited = $data2[0];
		$balance = $balance + $amountcredited;
		if ($balance < 0)
		{
			$balance = $balance * (0 - 1);
			insert_query ('tblcredit', array ('clientid' => $userid, 'date' => 'now()', 'description' => '' . 'Invoice #' . $invoiceid . ' Overpayment', 'amount' => $balance, 'relid' => $invoiceid));
			$query = '' . 'UPDATE tblclients SET credit=credit+' . $balance . ' WHERE id=\'' . $userid . '\'';
			$result = mysql_query ($query);
		}
	}

}

function refundinvoicepayment ($transid, $amount, $sendtogateway)
{
	$result = select_query ('tblaccounts', '', array ('id' => $transid));
	$data = mysql_fetch_array ($result);
	$userid = $data['userid'];
	$invoiceid = $data['invoiceid'];
	$gateway = $data['gateway'];
	$fullamount = $data['amountin'];
	$fees = $data['fees'];
	$gatewaytransid = $data['transid'];
	$rate = $data['rate'];
	$result = select_query ('tblaccounts', 'SUM(amountout)', array ('refundid' => $transid));
	$data = mysql_fetch_array ($result);
	$alreadyrefunded = $data[0];
	$fullamount -= $alreadyrefunded;
	if ($fullamount < $amount)
	{
		return 'amounterror';
	}

	if (!$amount)
	{
		$amount = $fullamount;
	}

	$result = select_query ('tblpaymentgateways', 'value', array ('gateway' => $gateway, 'setting' => 'convertto'));
	$data = mysql_fetch_array ($result);
	$convertto = $data['value'];
	if ($convertto)
	{
		$result = select_query ('tblclients', 'currency', array ('id' => $userid));
		$data = mysql_fetch_array ($result);
		$fromcurrencyid = $data['currency'];
		$convertedamount = convertcurrency ($amount, $fromcurrencyid, $convertto, $rate);
	}

	if ($gateway)
	{
		$params = getccvariables ($invoiceid);
	}

	if (($sendtogateway AND function_exists ($gateway . '_refund')))
	{
		$params['amount'] = ($convertedamount ? $convertedamount : $amount);
		$params['transid'] = $gatewaytransid;
		$params['paymentmethod'] = $gateway;
		$gatewayresult = call_user_func ($gateway . '_refund', $params);
		$refundtransid = $gatewayresult['transid'];
		$rawdata = $gatewayresult['rawdata'];
		$gatewayresult = $gatewayresult['status'];
		$result = select_query ('tblpaymentgateways', 'value', array ('gateway' => $gateway, 'setting' => 'name'));
		$data = mysql_fetch_array ($result);
		$gatewayname = $data['value'];
		logtransaction ($gatewayname . ' Refund', $rawdata, ucfirst ($gatewayresult));
	}
	else
	{
		$gatewayresult = 'manual';
		run_hook ('ManualRefund', array ('transid' => $transid, 'amount' => $amount));
	}

	if (($gatewayresult == 'success' OR $gatewayresult == 'manual'))
	{
		addtransaction ($userid, 0, '' . 'Refund of Transaction ID ' . $gatewaytransid, 0, $fees * (0 - 1), $amount, $gateway, $refundtransid, $invoiceid, '', $transid, $rate);
		logactivity ('' . 'Refunded Invoice Payment - Invoice ID: ' . $invoiceid . ' - Transaction ID: ' . $transid);
		$result = select_query ('tblinvoices', 'total', array ('id' => $invoiceid));
		$data = mysql_fetch_array ($result);
		$invoicetotal = $data[0];
		if ($fullamount == $amount)
		{
			update_query ('tblinvoices', array ('status' => 'Refunded'), array ('id' => $invoiceid));
			run_hook ('InvoiceRefunded', array ('invoiceid' => $invoiceid));
		}
	}

	return $gatewayresult;
}

function processpaidinvoice ($invoiceid, $noemail = '')
{
	global $CONFIG;
	$result = select_query ('tblinvoices', '', array ('id' => $invoiceid));
	$data = mysql_fetch_array ($result);
	$invoicestatus = $data['status'];
	$invoicenum = $data['invoicenum'];
	if ($invoicestatus != 'Unpaid')
	{
		return false;
	}

	update_query ('tblinvoices', array ('status' => 'Paid', 'datepaid' => 'now()'), array ('id' => $invoiceid));
	logactivity ('' . 'Invoice Marked Paid - Invoice ID: ' . $invoiceid);
	if (($CONFIG['SequentialInvoiceNumbering'] AND !$invoicenum))
	{
		$invoicenumber = $CONFIG['SequentialInvoiceNumberFormat'];
		$invoicenumber = str_replace ('{NUMBER}', $CONFIG['SequentialInvoiceNumberValue'], $invoicenumber);
		update_query ('tblconfiguration', array ('value' => '+1'), array ('setting' => 'SequentialInvoiceNumberValue'));
		update_query ('tblinvoices', array ('invoicenum' => $invoicenumber), array ('id' => $invoiceid));
		++$CONFIG['SequentialInvoiceNumberValue'];
	}

	if (!$noemail)
	{
		sendmessage ('Invoice Payment Confirmation', $invoiceid);
	}

	$result = select_query ('tblinvoiceitems', '', 'invoiceid=\'' . mysql_real_escape_string ($invoiceid) . '\' AND type!=\'\'', 'id', 'ASC');
	while ($data = mysql_fetch_array ($result))
	{
		$type = $data['type'];
		$relid = $data['relid'];
		if ($type == 'Hosting')
		{
			makehostingpayment ($relid);
			continue;
		}
		else
		{
			if ($type == 'Domain')
			{
				makedomainpayment ($relid);
				continue;
			}
			else
			{
				if ($type == 'Addon')
				{
					makeaddonpayment ($relid);
					continue;
				}
				else
				{
					if ($type == 'Upgrade')
					{
						require_once dirname (__FILE__) . '/upgradefunctions.php';
						processupgradepayment ($relid, '', '', 'true');
						continue;
					}
					else
					{
						if ($type == 'AddFunds')
						{
							insert_query ('tblcredit', array ('clientid' => $data['userid'], 'date' => 'now()', 'description' => '' . 'Add Funds Invoice #' . $invoiceid, 'amount' => $data['amount'], 'relid' => $invoiceid));
							$query3 = 'UPDATE tblclients SET credit=credit+' . $data['amount'] . ' WHERE id=\'' . $data['userid'] . '\'';
							$result3 = mysql_query ($query3);
							continue;
						}

						continue;
					}

					continue;
				}

				continue;
			}

			continue;
		}
	}

	run_hook ('InvoicePaid', array ('invoiceid' => $invoiceid));
}

function gettaxrate ($level, $state, $country)
{
	global $_LANG;
	$result = select_query ('tbltax', '', array ('level' => $level, 'state' => $state, 'country' => $country));
	$data = mysql_fetch_array ($result);
	$taxname = $data['name'];
	$taxrate = $data['taxrate'];
	if (!$taxrate)
	{
		$result = select_query ('tbltax', '', array ('level' => $level, 'state' => '', 'country' => $country));
		$data = mysql_fetch_array ($result);
		$taxname = $data['name'];
		$taxrate = $data['taxrate'];
	}

	if (!$taxrate)
	{
		$result = select_query ('tbltax', '', array ('level' => $level, 'state' => '', 'country' => ''));
		$data = mysql_fetch_array ($result);
		$taxname = $data['name'];
		$taxrate = $data['taxrate'];
	}

	if (!$taxrate)
	{
		$taxrate = 0;
	}

	if (!$taxname)
	{
		$taxname = $_LANG['invoicestax'];
	}

	return array ('name' => $taxname, 'rate' => $taxrate);
}

function pdfinvoice ($id)
{
	global $CONFIG;
	global $_LANG;
	global $currency;
	$result = select_query ('tblpaymentgateways', 'gateway,value', array ('setting' => 'name'), 'order', 'ASC');
	while ($data = mysql_fetch_array ($result))
	{
		$gatewaysarray[$data['gateway']] = $data['value'];
	}

	$result = select_query ('tblinvoices', '', array ('id' => $id));
	$data = mysql_fetch_array ($result);
	$invoiceid = $data['id'];
	$invoicenum = $data['invoicenum'];
	$userid = $data['userid'];
	$datecreated = $data['date'];
	$duedate = $data['duedate'];
	$subtotal = $data['subtotal'];
	$credit = $data['credit'];
	if ($CONFIG['TaxEnabled'])
	{
		$tax = $data['tax'];
		$tax2 = $data['tax2'];
		$taxrate = $data['taxrate'];
		$taxrate2 = $data['taxrate2'];
	}
	else
	{
		$taxrate = '0.00';
		$taxrate2 = '0.00';
	}

	$total = $data['total'];
	$status = $data['status'];
	$paymentmethod = $data['paymentmethod'];
	$paymentmethod = html_entity_decode ($gatewaysarray[$paymentmethod]);
	$notes = $data['notes'];
	$datepaid = $data['datepaid'];
	$datecreated = frommysqldate ($datecreated);
	$datepaid = frommysqldate ($datepaid, 'time');
	$duedate = frommysqldate ($duedate);
	$currency = getcurrency ($userid);
	$subtotal = formatcurrency ($subtotal);
	$credit = formatcurrency ($credit);
	$tax = formatcurrency ($tax);
	$tax2 = formatcurrency ($tax2);
	$total = formatcurrency ($total);
	if (!$invoicenum)
	{
		$invoicenum = $invoiceid;
	}

	if (!function_exists ('getClientsDetails'))
	{
		require_once dirname (__FILE__) . '/clientfunctions.php';
	}

	$clientsdetails = getclientsdetails ($userid, 'billing');
	if ($CONFIG['TaxEnabled'])
	{
		if (0 < $taxrate)
		{
			$taxname = gettaxrate (1, $clientsdetails['state'], $clientsdetails['country']);
			$taxname = $taxname['name'];
		}

		if (0 < $taxrate2)
		{
			$taxname2 = gettaxrate (2, $clientsdetails['state'], $clientsdetails['country']);
			$taxname2 = $taxname2['name'];
		}
	}

	require dirname (__FILE__) . '/countries.php';
	$clientsdetails['country'] = $countries[$clientsdetails['country']];
	foreach ($clientsdetails as $k => $v)
	{
		$clientsdetails[$k] = html_entity_decode ($v);
	}

	$companyname = html_entity_decode ($CONFIG['CompanyName']);
	$companyurl = $CONFIG['Domain'];
	$companyaddress = html_entity_decode ($CONFIG['InvoicePayTo']);
	$companyaddress = explode ('
', $companyaddress);
	$result = select_query ('tblinvoiceitems', '', array ('invoiceid' => $id), 'id', 'ASC');
	while ($data = mysql_fetch_array ($result))
	{
		$invoiceitems[] = array ('description' => html_entity_decode ($data['description']), 'amount' => formatcurrency ($data['amount']), 'taxed' => $data['taxed']);
	}

	$l = array ();
	$l['a_meta_charset'] = $CONFIG['Charset'];
	$l['a_meta_dir'] = 'ltr';
	$l['a_meta_language'] = 'en';
	$l['w_page'] = 'page';
	if (strtoupper ($CONFIG['Charset']) == 'UTF-8')
	{
		$pdf = new TCPDF ('P', 'mm', 'A4');
	}
	else
	{
		$pdf = new TCPDF ('P', 'mm', 'A4', false, $CONFIG['Charset']);
	}
                       /* Cleaned + Removed! */
  	$pdf->SetCreator ('FLIPMODE! v' . $CONFIG['Version']);
	$pdf->SetAuthor ($CONFIG['CompanyName']);
	$pdf->SetTitle ($_LANG['invoicenumber'] . $invoicenum);
	$pdf->setPrintHeader (false);
	$pdf->SetDefaultMonospacedFont (PDF_FONT_MONOSPACED);
	$pdf->SetMargins (PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
	$pdf->SetAutoPageBreak (TRUE, PDF_MARGIN_BOTTOM);
	$pdf->setImageScale (PDF_IMAGE_SCALE_RATIO);
	$pdf->setLanguageArray ($l);
	$pdf->SetFont ('helvetica', '', 10);
	$pdf->AddPage ();
	include ROOTDIR . '/templates/' . $CONFIG['Template'] . '/invoicepdf.tpl';
	$pdfdata = $pdf->Output ('Invoice.pdf', 'S');
	return $pdfdata;
}

function makehostingpayment ($func_domainid)
{
	global $CONFIG;
	$result = select_query ('tblhosting', '', array ('id' => $func_domainid));
	$data = mysql_fetch_array ($result);
	$userid = $data['userid'];
	$billingcycle = $data['billingcycle'];
	$domain = $data['domain'];
	$packageid = $data['packageid'];
	$regdate = $data['regdate'];
	$nextduedate = $data['nextduedate'];
	$status = $data['domainstatus'];
	$server = $data['server'];
	$paymentmethod = $data['paymentmethod'];
	$result = select_query ('tblproducts', '', array ('id' => $packageid));
	$data = mysql_fetch_array ($result);
	$producttype = $data['type'];
	$package = $data['name'];
	$module = $data['servertype'];
	$proratabilling = $data['proratabilling'];
	$proratadate = $data['proratadate'];
	$proratachargenextmonth = $data['proratachargenextmonth'];
	$autosetup = $data['autosetup'];
	if (($regdate == $nextduedate AND $proratabilling))
	{
		$orderyear = substr ($regdate, 0, 4);
		$ordermonth = substr ($regdate, 5, 2);
		$orderday = substr ($regdate, 8, 2);
		$proratavalues = getproratavalues ($billingcycle, $product_onetime, $proratadate, $proratachargenextmonth, $orderday, $ordermonth, $orderyear);
		$proratadateuntil = $proratavalues['date'];
	}

	$nextduedate = getinvoicepayuntildate ($nextduedate, $billingcycle, true);
	if ($proratadateuntil)
	{
		$nextduedate = $proratadateuntil;
	}

	update_query ('tblhosting', array ('nextduedate' => $nextduedate, 'nextinvoicedate' => $nextduedate), array ('id' => $func_domainid));
	if (!function_exists ('getModuleType'))
	{
		require_once dirname (__FILE__) . '/modulefunctions.php';
	}

	if ((($status == 'Pending' AND $autosetup == 'payment') AND $module))
	{
		logactivity ('Running Module Create on Payment');
		require_once ROOTDIR . '/modules/servers/' . $module . '/' . $module . '.php';
		$result = servercreateaccount ($func_domainid);
		if ($result == 'success')
		{
			sendmessage ('defaultnewacc', $func_domainid);
			sendadminnotification ('account', 'Automatic Setup Notification', '' . '<p>The order placed for ' . $domain . ' has received its first payment and has been automatically setup</p><p>Client ID: ' . $userid . '<br>Product/Service: ' . $package . '<br>Domain: ' . $domain . '</p>');
		}
		else
		{
			sendadminnotification ('account', 'Automatic Setup Notification', '' . '<p>The order placed for ' . $domain . ' has received its first payment but an error occured and the account could not be automatically setup on the server</p><p>Client ID: ' . $userid . '<br>Product/Service: ' . $package . '<br>Domain: ' . $domain . '<br>Error: ' . $result . '</p>');
		}
	}

	if ((($status == 'Suspended' AND $CONFIG['AutoUnsuspend'] == 'on') AND $module))
	{
		logactivity ('Running Auto Unsuspend on Payment');
		require_once ROOTDIR . '/modules/servers/' . $module . '/' . $module . '.php';
		serverunsuspendaccount ($func_domainid);
		sendadminnotification ('account', 'Automatic Unsuspension Notification', '' . '<p>The order placed for ' . $domain . ' has received its next payment and has been automatically unsuspended</p><p>Client ID: ' . $userid . '<br>Product/Service: ' . $package . '<br>Domain: ' . $domain . '</p>');
	}

	affiliatepayment ('', $func_domainid);
}

function makedomainpayment ($func_domainid)
{
	global $CONFIG;
	$result = select_query ('tbldomains', '', array ('id' => $func_domainid));
	$data = mysql_fetch_array ($result);
	$userid = $data['userid'];
	$domaintype = $data['type'];
	$orderid = $data['orderid'];
	$registrationperiod = $data['registrationperiod'];
	$registrationdate = $data['registrationdate'];
	$nextduedate = $data['nextduedate'];
	$amount = $data['amount'];
	$domain = $data['domain'];
	$paymentmethod = $data['paymentmethod'];
	$registrar = $data['registrar'];
	$status = $data['status'];
	$year = substr ($nextduedate, 0, 4);
	$month = substr ($nextduedate, 5, 2);
	$day = substr ($nextduedate, 8, 2);
	$newnextduedate = date ('Y-m-d', mktime (0, 0, 0, $month, $day, $year + $registrationperiod));
	update_query ('tbldomains', array ('nextduedate' => $newnextduedate), array ('id' => $func_domainid));
	$userid = ltrim ($userid, 0);
	$domainparts = explode ('.', $domain, 2);
	$sld = $domainparts[0];
	$tld = $domainparts[1];
	$params = array ();
	$params['domainid'] = $func_domainid;
	$params['sld'] = $sld;
	$params['tld'] = $tld;
	require_once dirname (__FILE__) . '/registrarfunctions.php';
	if ($status == 'Pending')
	{
		$result = select_query ('tbldomainpricing', 'autoreg', array ('extension' => '' . '.' . $tld));
		$data = mysql_fetch_array ($result);
		$autoreg = $data['autoreg'];
		if ($autoreg)
		{
			$table = 'tbldomains';
			$fields = '';
			$fields = array ('registrar' => $autoreg);
			$where = '' . 'id=\'' . $func_domainid . '\'';
			update_query ($table, $fields, $where);
			$params['registrar'] = $autoreg;
			if ($domaintype == 'Register')
			{
				logactivity ('Running Automatic Domain Registration on Payment');
				$result = regregisterdomain ($params);
				$emailmessage = 'Domain Registration Confirmation';
			}
			else
			{
				if ($domaintype == 'Transfer')
				{
					logactivity ('Running Automatic Domain Transfer on Payment');
					$result = regtransferdomain ($params);
					$emailmessage = 'Domain Transfer Initiated';
				}
			}

			$result = $result['error'];
			if ($result)
			{
				sendadminnotification ('account', 'Automatic Domain Registration Failure Notification', '' . '<p>The order placed for ' . $domain . ' has received its first payment and has been automatically submitted to the registrar</p><p>Client ID: ' . $userid . '<br>Domain: ' . $domain . '<br>Error: ' . $result . '</p>');
				if ($domaintype == 'Register')
				{
					$array = array ('date' => 'now()', 'title' => 'Manual Domain Registration', 'description' => '' . 'Client ID ' . $userid . ' has paid for the registration of domain ' . $domain . ' and the automated registration attempt has failed with the following error: ' . $result, 'admin' => '', 'status' => 'Pending', 'duedate' => date ('Y-m-d'));
				}
				else
				{
					if ($domaintype == 'Transfer')
					{
						$array = array ('date' => 'now()', 'title' => 'Manual Domain Transfer', 'description' => '' . 'Client ID ' . $userid . ' has paid for the transfer of domain ' . $domain . ' and the automated transfer attempt has failed with the following error: ' . $result, 'admin' => '', 'status' => 'Pending', 'duedate' => date ('Y-m-d'));
					}
				}

				insert_query ('tbltodolist', $array);
			}
			else
			{
				sendmessage ($emailmessage, $func_domainid);
				sendadminnotification ('account', 'Automatic Domain Registration Success Notification', '' . '<p>The order placed for ' . $domain . ' has received its first payment and has been automatically submitted to the registrar</p><p>Client ID: ' . $userid . '<br>Domain: ' . $domain . '</p>');
			}
		}
		else
		{
			if ($domaintype == 'Register')
			{
				$array = array ('date' => 'now()', 'title' => 'Manual Domain Registration', 'description' => '' . 'Client ID ' . $userid . ' has paid for the registration of domain ' . $domain, 'admin' => '', 'status' => 'Pending', 'duedate' => date ('Y-m-d'));
			}
			else
			{
				if ($domaintype == 'Transfer')
				{
					$array = array ('date' => 'now()', 'title' => 'Manual Domain Transfer', 'description' => '' . 'Client ID ' . $userid . ' has paid for the transfer of domain ' . $domain, 'admin' => '', 'status' => 'Pending', 'duedate' => date ('Y-m-d'));
				}
			}

			insert_query ('tbltodolist', $array);
		}
	}

	if (((($status != 'Pending' AND $status != 'Cancelled') AND $status != 'Fraud') AND $registrationdate < $nextduedate))
	{
		if (($CONFIG['AutoRenewDomainsonPayment'] AND $registrar))
		{
			logactivity ('Running Automatic Domain Renewal on Payment');
			$params['registrar'] = $registrar;
			$result = regrenewdomain ($params);
			$result = $result['error'];
			if ($result)
			{
				sendadminnotification ('account', 'Automatic Domain Renewal Failure Notification', '' . '<p>The invoice for the renewal of ' . $domain . ' has been paid and the renewal request has been automatically submitted to the registrar</p><p>Client ID: ' . $userid . '<br>Domain: ' . $domain . '<br>Error: ' . $result . '</p>');
				$array = array ('date' => 'now()', 'title' => 'Manual Domain Renewal', 'description' => '' . 'Client ID ' . $userid . ' has paid for the renewal of domain ' . $domain . ' and the automated renewal attempt has failed with the following error: ' . $result, 'admin' => '', 'status' => 'Pending', 'duedate' => date ('Y-m-d'));
				insert_query ('tbltodolist', $array);
				return null;
			}

			sendmessage ('Domain Renewal Confirmation', $func_domainid);
			sendadminnotification ('account', 'Automatic Domain Renewal Success Notification', '' . '<p>The invoice for the renewal of ' . $domain . ' has been paid and the renewal request has been automatically submitted to the registrar</p><p>Client ID: ' . $userid . '<br>Domain: ' . $domain . '</p>');
			return null;
		}

		$array = array ('date' => 'now()', 'title' => 'Manual Domain Renewal', 'description' => '' . 'Client ID ' . $userid . ' has paid for the renewal of domain ' . $domain, 'admin' => '', 'status' => 'Pending', 'duedate' => date ('Y-m-d'));
		insert_query ('tbltodolist', $array);
	}

}

function makeaddonpayment ($func_addonid)
{
	global $CONFIG;
	$result = select_query ('tblhostingaddons', '', array ('id' => $func_addonid));
	$data = mysql_fetch_array ($result);
	$id = $data['id'];
	$hostingid = $data['hostingid'];
	$addonid = $data['addonid'];
	$regdate = $data['regdate'];
	$name = $data['name'];
	$setupfee = $data['setupfee'];
	$recurring = $data['recurring'];
	$billingcycle = $data['billingcycle'];
	$free = $data['free'];
	$status = $data['status'];
	$nextduedate = $data['nextduedate'];
	$paymentmethod = $data['paymentmethod'];
	if ($regdate == $nextduedate)
	{
		$amount = $setupfee + $recurring;
	}
	else
	{
		$amount = $recurring;
	}

	if ($gateway)
	{
		$paymentmethod = $gateway;
	}

	$result = select_query ('tblhosting', '', array ('id' => $hostingid));
	$data = mysql_fetch_array ($result);
	$userid = $data['userid'];
	$domain = $data['domain'];
	if (substr ($regdate, 0, 8) == substr ($nextduedate, 0, 8))
	{
		$recurring = $setupfee;
	}

	$nextduedate = getinvoicepayuntildate ($nextduedate, $billingcycle, true);
	update_query ('tblhostingaddons', array ('nextduedate' => $nextduedate), array ('id' => $func_addonid));
	if ($status == 'Pending')
	{
		$result = select_query ('tbladdons', 'autoactivate,welcomeemail', array ('id' => $addonid));
		$data = mysql_fetch_array ($result);
		$autoactivate = $data['autoactivate'];
		$welcomeemail = $data['welcomeemail'];
		if ($autoactivate)
		{
			update_query ('tblhostingaddons', array ('status' => 'Active'), array ('id' => $func_addonid));
			if ($welcomeemail)
			{
				$result = select_query ('tblemailtemplates', 'name', array ('id' => $welcomeemail));
				$data = mysql_fetch_array ($result);
				$welcomeemailname = $data['name'];
				sendmessage ($welcomeemailname, $hostingid);
			}

			run_hook ('AddonActivation', array ('id' => $func_addonid, 'userid' => $userid, 'serviceid' => $hostingid, 'addonid' => $addonid));
		}
	}

	if ($status == 'Suspended')
	{
		update_query ('tblhostingaddons', array ('status' => 'Active'), array ('id' => $func_addonid));
	}

}

function getproratavalues ($billingcycle, $amount, $proratadate, $proratachargenextmonth, $day, $month, $year)
{
	$billingcycle = str_replace ('-', '', strtolower ($billingcycle));
	if ($billingcycle == 'monthly')
	{
		$proratamonths = 1;
	}
	else
	{
		if ($billingcycle == 'quarterly')
		{
			$proratamonths = 3;
		}
		else
		{
			if ($billingcycle == 'semiannually')
			{
				$proratamonths = 6;
			}
			else
			{
				if ($billingcycle == 'annually')
				{
					$proratamonths = 12;
				}
				else
				{
					if ($billingcycle == 'biennially')
					{
						$proratamonths = 24;
					}
				}
			}
		}
	}

	if ($billingcycle != 'monthly')
	{
		$proratachargenextmonth = 0;
	}

	if ($billingcycle == 'monthly')
	{
		if ($day < $proratadate)
		{
			$proratamonth = $month;
		}
		else
		{
			$proratamonth = $month + 1;
		}
	}
	else
	{
		$proratamonth = $month + $proratamonths;
	}

	$proratadateuntil = date ('Y-m-d', mktime (0, 0, 0, $proratamonth, $proratadate, $year));
	$monthnumdays = array ('31', '28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31');
	if ((($year % 4 == 0 AND $year % 100 != 0) OR $year % 400 == 0))
	{
		$monthnumdays[1] = 29;
	}

	$totaldays = 0;
	if ($billingcycle == 'monthly')
	{
		if (((($proratachargenextmonth < $proratadate AND $day < $proratadate) AND $proratachargenextmonth <= $day) OR (($proratadate <= $proratachargenextmonth AND $proratadate <= $day) AND $proratachargenextmonth <= $day)))
		{
			++$proratamonth;
		}

		$proratadateuntil = date ('Y-m-d', mktime (0, 0, 0, $proratamonth, $proratadate, $year));
		if (12 < $proratamonth)
		{
			$proratamonth = $proratamonth - 12;
		}

		$totaldays = $monthnumdays[$proratamonth - 1];
	}
	else
	{
		$counter = 1;
		while ($counter <= $proratamonths)
		{
			$month2 = $counter;
			if (12 < $month2)
			{
				$month2 = $month2 - 12;
			}

			$totaldays += $monthnumdays[$month2 - 1];
			++$counter;
		}
	}

	$days = ceil ((strtotime ($proratadateuntil) - strtotime ('' . $year . '-' . $month . '-' . $day)) / (60 * 60 * 24));
	$prorataamount = round ($amount * ($days / $totaldays), 2);
	return array ('amount' => $prorataamount, 'date' => $proratadateuntil);
}

?>